package com.gitee.easyopen.session;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;

import com.gitee.easyopen.ApiContext;

/**
 * SessionManager的redis实现，使用redis管理session
 * 
 * @author tanghc
 *
 */
public class RedisSessionManager implements SessionManager {

    private ApiRedisTemplate redisTemplate;

    private int sessionTimeout = 30; // 过期时间，30分钟

    public RedisSessionManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        Assert.notNull(redisTemplate, "RedisSessionManager中的redisTemplate不能为null");
        this.redisTemplate = new ApiRedisTemplate(redisTemplate.getConnectionFactory());
    }

    @Override
    public HttpSession getSession(String sessionId) {
        boolean existKey = this.hasKey(sessionId);
        if (existKey) {
            return RedisHttpSession.createExistSession(sessionId, getServletContext(), redisTemplate);
        } else {
            return RedisHttpSession.createNewSession(getServletContext(), sessionId, this.getSessionTimeout(),
                    redisTemplate);
        }
    }

    protected boolean hasKey(String sessionId) {
        if (sessionId == null) {
            return false;
        } else {
            String key = RedisHttpSession.buildKey(sessionId);
            return redisTemplate.hasKey(key);
        }
    }

    protected ServletContext getServletContext() {
        return ApiContext.getServletContext();
    }

    public int getSessionTimeout() {
        return sessionTimeout;
    }

    public void setSessionTimeout(int sessionTimeout) {
        this.sessionTimeout = sessionTimeout;
    }

    public ApiRedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(ApiRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

}
